package com.itfreer.gis.data.database;

import com.itfreer.file.LocalObjectBase;
import com.itfreer.gis.data.file.ShapeFileDataEditServer;
import com.itfreer.utils.zip.ZipperUtils;

import org.geotools.feature.FeatureCollection;
import org.geotools.geojson.feature.FeatureJSON;
import org.opengis.feature.simple.SimpleFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定义数据导入实现类
 */
@Component
public class DataImportServiceImp extends LocalObjectBase implements DataImportService {

	@Autowired
	private GeoToolsDataEditServer postGISDataEditServer;
	@Autowired
	private ShapeFileDataEditServer shapeFileAnalysis;
	@Autowired
	private DataExportService dataExportService;
	@Autowired
	protected PlatformTransactionManager transactionManager;

	/**
	 * 数据导入
	 *
	 * @param source
	 *            源数据，以zip为后缀的shape文件压缩包文件路径
	 * @param target
	 *            目录数据表名称
	 * @param where
	 *            从源数据中的过滤条件
	 * @return 返回数据库备份文件路径
	 * @throws Exception
	 */
	@Override
	public Map<String , Object> importShape(String source, String target, String where) throws Exception {
		// 解压文件
		String basePath = getBasePath();
		if (!basePath.endsWith("/")) {
			basePath += "/";
		}
		source = basePath + source;

		String unZipFile = source.replace(".ZIP", "").replace(".zip", "");
		File dir = new File(unZipFile);
		if (!dir.isDirectory()) {
			dir.mkdirs();
		}
		ZipperUtils.upZipFile(new File(source), unZipFile);
		FilenameFilter filter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.endsWith(".shp") || name.endsWith(".SHP");
			}
		};
		String[] children = dir.list(filter);
		if (children == null || children.length <= 0) {
			return null;
		}

		Map<String , Object> map = new HashMap<>();

		String shapeFile = unZipFile + "/" + children[0];
		// 1.准备好数据
		List<SimpleFeature> datas = shapeFileAnalysis.queryFeature(shapeFile, where);

		// 2.备份数据
		// 无需传入条件，拷贝相关数据库全部信息，导出成Shp文件并压缩
		String back = dataExportService.exportShape(target, target + "_back", where);
		// 3.导入数据
		// 配置事务策略
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setName("planOne-transaction");
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		// 设置状态点
		TransactionStatus status = transactionManager.getTransaction(def);
		try {
			// 3.删除数据
			postGISDataEditServer.deleteFeature(target, where);
			// 4.导入数据
			postGISDataEditServer.addFeatures(target, datas, null);
			transactionManager.commit(status);
			map.put("importData" , datas);
			map.put("backPath" , back);
			return map;
		} catch (Exception e) {
			transactionManager.rollback(status);
			throw e;
		}
	}

	/**
	 * 数据导入
	 *
	 * @param source
	 *            源数据，以zip为后缀的shape文件压缩包文件路径
	 * @param target
	 *            目录数据表名称
	 * @param where
	 *            从源数据中的过滤条件
	 * @return 返回数据库备份文件路径
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public String importGeoJson(String source, String target, String where) throws Exception {
		// 解压文件
		String basePath = getBasePath();
		if (!basePath.endsWith("/")) {
			basePath += "/";
		}
		source = basePath + source;

		String unZipFile = source.replace(".ZIP", "").replace(".zip", "");
		File dir = new File(unZipFile);
		if (!dir.isDirectory()) {
			dir.mkdirs();
		}
		ZipperUtils.upZipFile(new File(source), unZipFile);
		FilenameFilter filter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.endsWith(".geojson") || name.endsWith(".GEOJSON");
			}
		};
		String[] children = dir.list(filter);
		if (children == null || children.length <= 0) {
			return null;
		}

		// 1.准备好数据
		String shapeFile = unZipFile + "/" + children[0];
		FeatureJSON fjson = new FeatureJSON();
		InputStream inputStream = new FileInputStream(shapeFile);
		FeatureCollection featureCollection = fjson.readFeatureCollection(inputStream);
		List<SimpleFeature> datas = new ArrayList<>();
		SimpleFeature item = (SimpleFeature) featureCollection.features().next();
		if (item != null) {
			datas.add(item);
			while (featureCollection.features().hasNext()) {
				SimpleFeature next = (SimpleFeature) featureCollection.features().next();
				datas.add(next);
			}
		}

		// 2.备份数据
		// 无需传入条件，拷贝相关数据库全部信息，导出成Shp文件并压缩
		String back = dataExportService.exportShape(target, target + "_back", where);
		// 3.导入数据
		// 配置事务策略
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setName("planOne-transaction");
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		// 设置状态点
		TransactionStatus status = transactionManager.getTransaction(def);
		try {
			// 3.删除数据
			postGISDataEditServer.deleteFeature(target, where);
			// 4.导入数据
			postGISDataEditServer.addFeatures(target, datas, null);
			transactionManager.commit(status);
			return back;
		} catch (Exception e) {
			transactionManager.rollback(status);
			throw e;
		}
	}
}
